import { UserInfo } from '@/service/modules/user/types'
import { createStore } from 'vuex'

interface Pane {
  name: string
  path: string
  tab: string
  tabName: string
  attrs: {
    key?: number
  }
}
export default createStore({
  //数据，相当于data
  state: {
    userInfo: {},
    tabPanes: new Array<Pane>(),
    tabPaneSelected: ''
  },
  getters: {},
  //里面定义方法，操作state方发
  mutations: {
    updateUserInfo(state, userInfo: UserInfo) {
      state.userInfo = userInfo
    },
    addPane(state, pane: Pane) {
      const paneIndex = state.tabPanes.findIndex(
        (item) => item.name === pane.name
      )
      if (!~paneIndex) {
        pane.attrs.key = 0
        state.tabPanes.push(pane)
      }
      state.tabPaneSelected = pane.name
    },
    clearTabPanes(state) {
      state.tabPanes = new Array<Pane>()
    },
    updateTabPaneSelected(state, name: string) {
      const pane = state.tabPanes.find((item) => item.name === name)
      if (pane) {
        const newAttrs = { ...pane.attrs }
        delete newAttrs.key
        window.$router.push({
          path: pane.path,
          query: newAttrs
        })
      }
    },
    closePane(state, name: string) {
      const nameIndex = state.tabPanes.findIndex((item) => item.name === name)
      if (!~nameIndex) return
      state.tabPanes.splice(nameIndex, 1)
      if (name === state.tabPaneSelected) {
        const pane =
          state.tabPanes[Math.min(nameIndex, state.tabPanes.length - 1)]
        if (pane) {
          const newAttrs = { ...pane.attrs }
          delete newAttrs.key
          window.$router.push({
            path: pane.path,
            query: newAttrs
          })
        }
      }
    },
    closeOtherPane(state, name: string) {
      const pane = state.tabPanes.find((item) => item.name === name)
      if (pane) {
        state.tabPaneSelected = pane.name
        state.tabPanes.splice(0)
        state.tabPanes.push(pane)
      }
    },
    refreshCurrentPane(state) {
      const currentPane = state.tabPanes.find(
        (item) => item.name === state.tabPaneSelected
      )
      currentPane.attrs.key = currentPane.attrs.key + 1
    }
  },
  // 操作异步操作mutation
  actions: {},
  modules: {}
})
